import React, { useState, useEffect } from 'react';
import { Search, Filter, ChevronLeft, ChevronRight } from 'lucide-react';
import VideoGrid from '../components/VideoGrid';
import VideoPlayer from '../components/VideoPlayer';
import API_CONFIG from '../utils/apiConfig';

const categories = ["全部", "人", "车", "自行车", "头", "安全衣", "头盔"];
const ITEMS_PER_PAGE = 8;

const VideoGridPage = () => {
  const [videos, setVideos] = useState([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('全部');
  const [filteredVideos, setFilteredVideos] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [selectedVideo, setSelectedVideo] = useState(null);

    const [categories, setCategories] = useState([]);

  // Fetch categories from backend
  useEffect(() => {
    // Fetch categories from backend
    const fetchCategories = async () => {
      try {
        const response = await API_CONFIG.fetch('labels');
        
        if (response.ok) {
          const data = await response.json();
          // 使用map()方法提取label_text值到新数组
          const labelTexts = data.map(item => item.label_text);
          setCategories(['全部', ...labelTexts]); // 添加"全部"作为第一个分类
        }
        else {
          console.error('Error fetching categories X1:', error);
          // Fallback to hardcoded categories if API fails
          setCategories(categories);
        }
      } catch (error) {
        console.error('Error fetching categories X2:', error);
        setCategories(categories);
      }
    };

    fetchCategories();
     }, []);
  // Fetch videos from API
  useEffect(() => {
    const fetchVideos = async () => {
      try {
        const response = await fetch(
          `${API_CONFIG.baseURL}${API_CONFIG.endpoints.videos}`
        );
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.json();
        setVideos(data);
        setFilteredVideos(data);
        setError(null);
      } catch (err) {
        setError('无法加载视频数据');
        console.error('Error fetching videos:', err);
      } finally {
        setLoading(false);
      }
    };

    fetchVideos();
  }, []);

  // Filter videos based on search term and category
  useEffect(() => {
    let filtered = videos;

    // 按分类筛选
    if (selectedCategory !== '全部') {
      filtered = filtered.filter(video => video.object_labels.includes(selectedCategory));
    }

    // 按搜索词筛选
    if (searchTerm) {
      filtered = filtered.filter(video =>
        video.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
        video.channel.toLowerCase().includes(searchTerm.toLowerCase())
      );
    }

    setFilteredVideos(filtered);
    setCurrentPage(1); // Reset to first page when filters change
  }, [searchTerm, selectedCategory, videos]);

  // Calculate pagination values
  const totalPages = Math.ceil(filteredVideos.length / ITEMS_PER_PAGE);
  const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
  const endIndex = startIndex + ITEMS_PER_PAGE;
  const currentVideos = filteredVideos.slice(startIndex, endIndex);

  const handlePageChange = (page) => {
    setCurrentPage(page);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const renderPagination = () => {
    if (totalPages <= 1) return null;

    const pages = [];
    const maxVisiblePages = 10; // 从5改为10，以便一横条最多显示10页
    let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
    let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

    if (endPage - startPage + 1 < maxVisiblePages) {
      startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }

    // 首页按钮
    pages.push(
      <button
        key="first"
        onClick={() => handlePageChange(1)}
        disabled={currentPage === 1}
        className="pagination-btn"
      >
        首页
      </button>
    );

    // Previous button
    pages.push(
      <button
        key="prev"
        onClick={() => handlePageChange(currentPage - 1)}
        disabled={currentPage === 1}
        className="pagination-btn"
      >
        <ChevronLeft size={16} />
      </button>
    );

    // Page numbers
    for (let i = startPage; i <= endPage; i++) {
      pages.push(
        <button
          key={i}
          onClick={() => handlePageChange(i)}
          className={`pagination-btn ${currentPage === i ? 'active' : ''}`}
        >
          {i}
        </button>
      );
    }

    // Next button
    pages.push(
      <button
        key="next"
        onClick={() => handlePageChange(currentPage + 1)}
        disabled={currentPage === totalPages}
        className="pagination-btn"
      >
        <ChevronRight size={16} />
      </button>
    );

    // 末页按钮
    pages.push(
      <button
        key="last"
        onClick={() => handlePageChange(totalPages)}
        disabled={currentPage === totalPages}
        className="pagination-btn"
      >
        末页
      </button>
    );

    return (
      <div className="pagination">
        <span className="pagination-info">
          第 {currentPage} 页，共 {totalPages} 页 ({filteredVideos.length} 个视频)
        </span>
        <div className="pagination-controls">
          {pages}
        </div>
      </div>
    );
  };

  if (loading) {
    return (
      <div className="app">
        <header className="header">
          <div className="header-content">
            <h1 className="logo">视频监控中心</h1>
          </div>
        </header>
        <main className="main">
          <div className="loading">加载中...</div>
        </main>
      </div>
    );
  }

  if (error) {
    return (
      <div className="app">
        <header className="header">
          <div className="header-content">
            <h1 className="logo">视频监控中心</h1>
          </div>
        </header>
        <main className="main">
          <div className="error">
            <h3>{error}</h3>
            <p>请检查网络连接或稍后重试</p>
          </div>
        </main>
      </div>
    );
  }

  const handleVideoClick = (video) => {
    setSelectedVideo(video);
  };

  const handleClosePlayer = () => {
    setSelectedVideo(null);
  };

  return (
    <div className="app">
      <main className="main">
        <div className="filters">
          <div className="filter-row">
            <div className="search-container">
              <Search className="search-icon" />
              <input
                type="text"
                placeholder="搜索视频..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="search-input"
              />
            </div>
            
            <div className="category-filters">
              <Filter className="filter-icon" />
              <div className="category-buttons">
                {categories.map(category => (
                    <button
                      key={category}
                      onClick={() => setSelectedCategory(category)}
                      className={`category-btn ${selectedCategory === category ? 'active' : ''}`}
                    >
                      {category}
                    </button>
                  ))
                }
              </div>
            </div>
          </div>
        </div>

        <VideoGrid 
          videos={currentVideos} 
          onVideoClick={handleVideoClick}
        />

        {renderPagination()}

        {filteredVideos.length === 0 && !loading && (
          <div className="no-results">
            <h3>未找到视频</h3>
            <p>请调整搜索或筛选条件</p>
          </div>
        )}
      </main>
      <VideoPlayer 
        video={selectedVideo}
        onClose={handleClosePlayer}
      />
    </div>
  );
};

export default VideoGridPage;